/***************************************************
 ** @Desc : This file for 先锋通道列表以及增删改
 ** @Time : 2019.04.01 15:38 
 ** @Author : Joker
 ** @File : merchant
 ** @Last Modified by : Joker
 ** @Last Modified time: 2019.04.01 15:38
 ** @Software: GoLand
****************************************************/
package controllers

import (
	"recharge/controllers/implement"
	"recharge/models"
	"recharge/utils"
	"strconv"
	"strings"
)

type XFMerchant struct {
	KeepSession
}

var merchantMdl = models.Merchant{}
var merchantImpl = implement.MerchantImpl{}
var AES = utils.AES{}

// 展示首页
// @router /merchant/ [get,post]
func (the *XFMerchant) ShowIndex() {
	userName := the.GetSession("userName")
	if userName != nil {
		the.Data["userName"] = userName.(string)
	}
	right := the.GetSession("FilterRight")
	if right != nil {
		the.Data["right"] = right.(int)
	}

	userId := the.GetSession("userId").(int)
	userInfo ,_:= userMdl.SelectOneUserById(userId)
	the.Data["u"] = userInfo

	the.TplName = "index.html"
}

// 先锋道通列表展示
// @router /merchant/list_UI/ [get]
func (the *XFMerchant) ListMerchant() {
	userName := the.GetSession("userName")
	if userName != nil {
		the.Data["userName"] = userName.(string)
	}

	right := the.GetSession("FilterRight")
	if right != nil {
		the.Data["right"] = right.(int)
	}

	the.TplName = "merchant.html"
}

// 添加先锋通道
// @router /merchant/add_xf/?:params [post]
func (the *XFMerchant) AddXFMerchant() {
	xfMerchantName := strings.Trim(the.GetString("xf_merchant_name"), " ")
	xfMerchantNo := strings.Trim(the.GetString("xf_merchant_no"), " ")
	xfKey := strings.Trim(the.GetString("xf_key"), " ")

	var msg = utils.FAILED_STRING
	var flag = utils.FAILED_FLAG
	isExit := merchantMdl.MerchantNoIsExit(xfMerchantNo)
	if isExit {
		msg = "该商户编号已经存在！"
	} else {
		if xfMerchantName == "" {
			xfMerchantName = utils.XF + globalMethod.GetNowTimeV2()
		}

		xfMerchant := models.Merchant{}
		xfMerchant.MerchantName = xfMerchantName
		xfMerchant.MerchantNo = xfMerchantNo
		xfMerchant.SecretKey = xfKey
		xfMerchant.ChannelType = utils.XF
		xfMerchant.CreateTime = globalMethod.GetNowTime()
		xfMerchant.EditTime = xfMerchant.CreateTime

		flag, _ = merchantMdl.InsertMerchant(xfMerchant)

		// 更新商户金额
		// 注释掉的原因：
		// 更新商户余额的耗时超过了ajax响应时间，导致前端响应错误，虽然实际上可能没有错
		//if flag > 0 {
		//	// 更新
		//	msg1, flag1 := merchantImpl.UpdateMerchantAmount(xfMerchant, msg, flag)
		//	// 若msg1:"操作失败! "; flag1:-9
		//	// 则更新正常
		//	sys.LogInfo("添加商户后更新商户金额，msg：", msg1, "，flag：", flag1)
		//}
	}

	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, "")
	the.ServeJSON()
	the.StopRun()
}

// 通道列表查询分页
// @router /merchant/list_xf/?:params [get]
func (the *XFMerchant) QueryAndListPage() {
	//分页参数
	page, _ := strconv.Atoi(the.GetString("page"))
	limit, _ := strconv.Atoi(the.GetString("limit"))
	if limit == 0 {
		limit = 20
	}

	//查询参数
	in := make(map[string]interface{})
	merchantNo := strings.Trim(the.GetString("MerchantNo"), " ")
	merchantName := strings.Trim(the.GetString("MerchantName"), " ")

	in["merchant_no__icontains"] = merchantNo
	in["merchant_name__icontains"] = merchantName
	in["channel_type"] = utils.XF

	//TODO：本来是管理员添加的商户，其他管理不可见，注释掉则都可见
	//userId := the.GetSession("userId")
	//in["user_id"] = userId.(int)

	//计算分页数
	count := merchantMdl.SelectMerchantPageCount(in)
	totalPage := count / limit // 计算总页数
	if count%limit != 0 { // 不满一页的数据按一页计算
		totalPage++
	}

	//数据获取
	var list []models.Merchant
	if page <= totalPage {
		list = merchantMdl.SelectMerchantListPage(in, limit, (page-1)*limit)
	}

	//数据回显
	out := make(map[string]interface{})
	out["limit"] = limit //分页数据
	out["page"] = page
	out["totalPage"] = totalPage
	out["root"] = list //显示数据

	the.Data["json"] = out
	the.ServeJSON()
	the.StopRun()
}

//展示编辑页面
// @router /merchant/edit_xf_ui/?:params [get]
func (the *XFMerchant) ShowEditXFUI() {
	editId := the.GetString(":params")
	the.SetSession("edit_Id_xf", editId)

	XFMerchant := merchantMdl.SelectOneMerchant(editId)
	the.SetSession("edit_merchantNo_xf", XFMerchant.MerchantNo)

	the.Data["json"] = globalMethod.JsonFormat(utils.SUCCESS_FLAG, XFMerchant, "", "")
	the.ServeJSON()
	the.StopRun()
}

// 编辑先锋通道
// @router /merchant/edit_xf/?:params [post]
func (the *XFMerchant) EditXFMerchant() {
	xfMerchantName := strings.Trim(the.GetString("xf_merchant_name"), " ")
	xfMerchantNo := strings.Trim(the.GetString("xf_merchant_no"), " ")
	xfKey := strings.Trim(the.GetString("xf_key"), " ")

	var msg = utils.FAILED_STRING
	var flag = utils.FAILED_FLAG

	merchantNo := the.GetSession("edit_merchantNo_xf")
	if merchantNo == nil {
		msg = "浏览器请不要禁用cookie！"
	} else {
		//若没有修改商户编号,则不判断商户编号是否唯一
		var isExit = true
		if strings.Compare(merchantNo.(string), xfMerchantNo) == 0 {
			isExit = false
		}
		if isExit {
			isExit = merchantMdl.MerchantNoIsExit(xfMerchantNo)
		}

		if isExit {
			msg = "该商户编号已经存在！"
		} else {
			if xfMerchantName == "" {
				xfMerchantName = utils.XF + globalMethod.GetNowTimeV2()
			}

			editId := the.GetSession("edit_Id_xf")
			if editId == nil {
				msg = "浏览器请不要禁用cookie！"
			} else {
				xfMerchant := merchantMdl.SelectOneMerchant(editId.(string))
				xfMerchant.MerchantName = xfMerchantName
				xfMerchant.MerchantNo = xfMerchantNo
				xfMerchant.SecretKey = xfKey
				xfMerchant.EditTime = globalMethod.GetNowTime()

				flag = merchantMdl.UpdateMerchant(xfMerchant)
			}
		}
	}

	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, "")
	the.ServeJSON()
	the.StopRun()
}

// 删除商户
// @router /merchant/del_xf/?:params [get]
func (the *XFMerchant) RemoveXFMerchant() {
	delId := the.GetString(":params")

	XFMerchant := merchantMdl.SelectOneMerchant(delId)
	XFMerchant.Status = 1
	XFMerchant.EditTime = globalMethod.GetNowTime()

	flag := merchantMdl.UpdateMerchant(XFMerchant)

	the.Data["json"] = globalMethod.GetDatabaseStatus(flag)
	the.ServeJSON()
	the.StopRun()
}

// 展示修改个人信息界面
// @router /merchant/edit_userInfo_ui/ [get]
func (the *XFMerchant) ShowEditUserInfoUI() {
	userName := the.GetSession("userName")
	if userName != nil {
		the.Data["userName"] = userName.(string)
	}

	right := the.GetSession("FilterRight")
	if right != nil {
		the.Data["right"] = right.(int)
	}

	the.TplName = "edit_userinfo.html"
}

// 修改个人信息发送短信验证码
// @router /merchant/edit_userInfo_sms/?:params [post]
func (the *XFMerchant) SendMsgEditUserInfo() {
	cemail := strings.Trim(the.GetString("cemail"), " ")
	newCemail := strings.Trim(the.GetString("new_cemail"), " ")

	var msg = utils.FAILED_STRING
	var flag = utils.FAILED_FLAG

	msg, verify := merchantImpl.VerificationUserInfo(cemail, newCemail)
	if verify {
		loginName := the.GetSession("FilterUsers")
		if loginName == nil {
			msg = "浏览器请不要禁用cookie！"
		} else {
			u := userMdl.SelectOneUser(loginName.(string))

			editCookie := the.Ctx.GetCookie("edit_userInfo_cookie")
			if editCookie == "" {
				the.SetSession("edit_userInfo_cookie", "")
			}

			cookieS := the.GetSession("edit_userInfo_cookie")
			codeCookie := ""
			if cookieS != nil {
				codeCookie = cookieS.(string)
			}

			if editCookie != "" || strings.Compare(editCookie, codeCookie) != 0 {
				msg = "请在2分钟后送登录验证码！"
			} else {
				code := globalMethod.RandomIntOfString(6)
				isSuccess := sms.SendSmsCode(u.Mobile, code)
				if !isSuccess {
					msg = "验证码发送失败，请联系管理员核实预留手机号是否正确！"
				} else {
					flag = utils.SUCCESS_FLAG
					the.SetSession("edit_userInfo_code", code)

					cookie := globalMethod.RandomString(6)
					the.Ctx.SetCookie("edit_userInfo_cookie", cookie, 2*60)
					the.SetSession("edit_userInfo_cookie", cookie)

					msg = "验证码发送成功，且2分钟内有效！"
				}
			}
		}
	}

	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, "")
	the.ServeJSON()
	the.StopRun()
}

// 修改个人信息
// @router /merchant/edit_userInfo/?:params [post]
func (the *XFMerchant) EditUserInfo() {
	cname := strings.Trim(the.GetString("cname"), " ")
	cemail := strings.Trim(the.GetString("cemail"), " ")
	newCemail := strings.Trim(the.GetString("new_cemail"), " ")
	mobileCode := strings.Trim(the.GetString("mobile_code"), " ")

	var msg = utils.FAILED_STRING
	var flag = utils.FAILED_FLAG

	msg, flag = checkUserInfo(msg, cemail, newCemail, the, mobileCode, cname, flag)

	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, "")
	the.ServeJSON()
	the.StopRun()
}

// 核对修改用户信息
func checkUserInfo(msg string, cemail string, newCemail string, the *XFMerchant, mobileCode string, cname string, flag int) (string, int) {
	msg, verify := merchantImpl.VerificationUserInfo(cemail, newCemail)
	if verify {
		loginName := the.GetSession("FilterUsers")
		if loginName == nil {
			return "浏览器请不要禁用cookie！", flag
		}

		//短信验证码
		loginCode := the.GetSession("edit_userInfo_code")
		if loginCode == nil {
			return "请发送手机验证码！", flag
		}

		if strings.Compare(loginCode.(string), mobileCode) != 0 {
			return "短信验证码输入错误！", flag
		}

		u := userMdl.SelectOneUser(loginName.(string))
		pwdMd5 := globalMethod.LoginPasswordSolt(cemail, u.Salt)
		if strings.Compare(pwdMd5, u.LoginPwd) != 0 {
			return "原始密码输入错误!", flag
		}

		u.LoginPwd, u.Salt = globalMethod.PasswordSolt(newCemail)
		if cname != "" {
			u.UserName = cname
		}
		u.EditTime = globalMethod.GetNowTime()

		flag = userMdl.UpdateUserInfo(u)

		//若更新成功.用户需要重新登录
		if flag > 0 {
			the.DelSession("FilterUsers")
			the.DelSession("FilterRight")
			the.DelSession("userName")
		}

		//两分钟失效
		cookie := the.Ctx.GetCookie("edit_userInfo_cookie")
		if cookie == "" {
			the.SetSession("edit_userInfo_code", "")
			the.SetSession("edit_userInfo_cookie", "")
		}
	}
	return msg, flag
}

// 更新道通金额
// @router /merchant/query_xf_balance/?:params [get]
func (the *XFMerchant) XFQueryBalance() {
	queryId := the.GetString(":params")

	var msg = utils.FAILED_STRING
	var flag = utils.FAILED_FLAG

	XFMerchant := merchantMdl.SelectOneMerchant(queryId)

	// 更新
	msg, flag = merchantImpl.UpdateMerchantAmount(XFMerchant, msg, flag)

	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, "")
	the.ServeJSON()
	the.StopRun()
}
